(function(){
    "use strict";
    var configManageController=function ($scope,$http,$modal,$location,projectstart_Service,online_testService,
        develop_processService,online_deliveryService,acceptanceService,toolsService){

        $scope.productId = toolsService.parameter("productId",$location.absUrl());
        //该项目是已有项目还是要创建的新项目
        $scope.isNew = true;
        //初始化项目下所有的产品的所有涉及人员信息
        $scope.operators = [];
        //初始化项目下所有的产品信息
        $scope.pros = [];
        $scope.finance = {};
        $scope.addedProductKey=[];
        //save功能-变量定义
        //初始化代码仓库类型和jenkins类型
        $scope.codeTypes=["SVN","GIT","GERRIT"];
        $scope.jenkinsTypes = ["java_coverage","php_coverage","python_coverage","findbugs_analysis","pylint_analysis","build_status"];
        //pipeline的配置参数
        $scope.vm = {};
        $scope.product = {};

        $scope.addedCoders = [];
        //添加测试人员
        $scope.addedTesters = [];
        var productList = JSON.parse(localStorage.getItem("productList"));
        var idIndex = 0;
        if (productList !== null && productList !== undefined && productList.length > 0){
            idIndex = productList[productList.length - 1].productId + 1;
            angular.forEach(productList,function (item) {
                if ($scope.productId !== null && item.productId === Number($scope.productId)){
                    idIndex = item.productId;
                    $scope.para = item;
                    $scope.isNew = false;
                    $scope.vm = item.pipeLine;
                    $scope.addedCoders = item.personKeyAndRoles.DE;
                    $scope.addedTesters = item.personKeyAndRoles.TM;
                    $scope.newProductName = item.productName;
                    $scope.newProductDes = item.description;
                    $scope.selectedJira = item.jira;
                    if ($scope.selectedJira !== null || $scope.selectedJira !== undefined){
                        $scope.jiraShowType = "detail";
                    }
                    $scope.selectedScm = item.scm;

                    if ($scope.selectedScm !== null || $scope.selectedScm !== undefined){
                        $scope.scmShowType = "detail";
                    }
                    $scope.selectedJenkins = item.jenkins;

                    if ($scope.selectedJenkins !== null || $scope.selectedJenkins !== undefined){
                        $scope.dailyJenkinsShowType = "detail";
                    }
                    $scope.tableData = item.testRecords;
                    if ($scope.tableData === null || $scope.testRecords === undefined || $scope.testRecords.length === 0){
                        $scope.testRecords = 0;
                    }
                }
            });
        }

        //根据是否是新项目来初始化$scope.vm的值
        $scope.valueVM =  function (isNew){
            if(isNew){
                $scope.vm = {
                    "config" : true,
                    "configCopy" : 'create',
                    "workflow" : {
                        "triggers" : true,
                        "tasks" : [
                            {   "itemId":1,
                                "selected" : false,
                                "isClick" : false,
                                "isSelectShow" : true
                            }
                        ]
                    },
                    "isConfig" : false,
                    "isUpdate" : false
                };
            }else{
                projectstart_Service.getPipeLineConfig({"productId" : $scope.productId}).success(function(data){
                    $scope.vm = data.result;
                    if($scope.vm.workflow.tasks.length>0) {
                        $scope.type = $scope.vm.workflow.tasks[0].type;
                    }
                });
            }
        };

        if ($scope.productId === null || $scope.productId === undefined){
            $scope.valueVM(true);
        }

        //删除pipe中某个task
        $scope.pipeLineRemove = function(index){
            if($scope.vm.workflow.tasks.length>1){
                $scope.vm.workflow.tasks.splice(index,1);
                //右边配置页面显示下一个task的配置项
                $scope.type = $scope.vm.workflow.tasks[index].type;
            }else if($scope.vm.workflow.tasks.length === 1){
                $scope.vm.workflow.tasks.splice(index,1);
                //右边配置页面显示下一个task的配置项
                $scope.type = {};
            }
        };

        //单击某个task显示task下拉框进行任务选择
        $scope.configTask = function(taskItem){
            //切换成task下拉选择框
            taskItem.isClick = true;
            taskItem.selected = true;
            if(taskItem.type === null || taskItem.type === undefined){
                //新增加一个task
                var task = {
                    "itemId":taskItem.itemId +1,
                    "selected" : false,
                    "isClick" : false,
                    "isSelectShow" : true
                };
                $scope.vm.workflow.tasks.push(task);
//                console.log("id:"+(task.id));
            }
        };

        //单击某个task进行任务配置页的显示
        $scope.configShow = function(taskItem){
            if(taskItem.type !== ""){
                console.log("$scope.type:"+taskItem.type);
                $scope.type = taskItem.type;
            }
        };

        //将具体的任务类型固定化
        $scope.taskStyle = [
            {
                "type" : "研发启动",
                "name" : "研发启动"
            },
            {
                "type" : "需求管理",
                "name" : "需求管理"
            },
            {
                "type" : "研发过程",
                "name" : "研发过程"
            },
            {
                "type" : "在线测试",
                "name" : "在线测试"
            },
            {
                "type" : "配置审计",
                "name" : "配置审计"
            }
/*            ,{
                "type" : "上线交付",
                "name" : "上线交付"
            }*/
        ];

        //当前需显示的任务配置页
        $scope.type = {};
        //选择任务类型的方法
        $scope.TSChoose = function(taskItem,selectedTS){
            var result = false;
            angular.forEach($scope.vm.workflow.tasks,function (item) {
                if( selectedTS.type === item.type && !result){
                    result = true;
                }
            });
            //隐藏选择框，显示任务名
            console.log(result);
            if(!result){
                taskItem.isSelectShow = false;
                if(selectedTS !== undefined){
                    taskItem.type = selectedTS.type;
                }
            }else{
                $scope.confirmModal(false,selectedTS.name+"已被选，请选择其他任务项!");
            }
        };

        //点击取消按钮，回到项目选择页面（不会执行保存动作）
        $scope.goBack = function (){
            //返回到前一个页面
            parent.iframe.location = "configManage.html";
            //如果项目启动已经保存，则执行后台删除操作(新建项目的操作)
            if($scope.vm.isUpdate === false && $scope.productId !== null){
                var productList = JSON.parse(localStorage.getItem("productList"));
                angular.forEach(productList,function (item) {
                    if (item.productId === $scope.productId){
                        productList.splice(item);
                    }
                })
            }
        };

        //查看tasks队列中是否只有一个"项目启动"的task
        $scope.checkIsConfig = function() {
/*            console.log("1111"+$scope.isNew);
            if($scope.isNew === false){
                return;
            }*/
            var result = false;
            var num = 0;
            angular.forEach($scope.vm.workflow.tasks, function(item) {
                if(item.type === "研发启动"){
                    num++;
                }
            });
            if(num === 1){
                result = true;
            }
            return result;
        };
        //监控上述方法的返回值
        $scope.$watch('checkIsConfig()', function(nv) {
            $scope.vm.isConfig = nv;
        });
        //save功能-变量定义
        var de_map=[];//开发者
        var tm_map=[];//测试人员
        //所有开发人员信息列表
        $scope.allCoders = [];
        //所有选中产品对应的开发人员信息
        $scope.allCodersGet = function (para){
            $scope.allCoders =
                [
                    {id:1,name:" 张三"},
                    {id:2,name:" 李四"},
                    {id:3,name:" 王五"},
                    {id:4,name:" 赵六"},
                    {id:5,name:" 汪诚益"},
                    {id:6,name:" 包军"}
                ];
        };
        $scope.allCodersGet();

        //添加开发人员
        $scope.coderChoose = function (){
            if($scope.selectedCoder!==undefined){
                $scope.addedCoders.push($scope.selectedCoder);
                de_map.push($scope.selectedCoder);
            }
        };

        //删除对应的选中的开发人员
        $scope.delCoders = function (index){
            $scope.selectedCoder = {};
            $scope.addedCoders.splice(index,1);
        };

        //所有测试人员信息列表
        $scope.allTesters = [];
        //所有选中产品对应的测试人员信息
        $scope.allTestersGet = function (para){
            $scope.allTesters =
                [
                    {id:1,name:" 张四"},
                    {id:2,name:" 李五"},
                    {id:3,name:" 王六"},
                    {id:4,name:" 赵七"},
                    {id:5,name:" 珊丹"}
                ];
        };
        $scope.allTestersGet();

        $scope.testerChoose = function (){
            if($scope.selectedTester!==undefined) {
                $scope.addedTesters.push($scope.selectedTester);
                tm_map.push($scope.selectedTester);
            }
        };

        //删除对应的选中的测试人员
        $scope.delTesters = function (index){
            $scope.selectedTester = {};
            $scope.addedTesters.splice(index,1);
        };
        //保存项目信息的方法(需加上错误提示对话框)
        $scope.saveProductInfo = function (){
            if($scope.newProductName === null || $scope.newProductName === undefined){
                $scope.confirmModal(false,"产品名称不能为空 !");
                return;
            }
            if(de_map === undefined || de_map.length <= 0){
                $scope.confirmModal(false,"请添加开发人员 !");
                return;
            }
            if(tm_map === undefined || tm_map.length <= 0){
                $scope.confirmModal(false,"请添加测试人员 !");
                return;
            }

            //入参增加objectid参数，后台判断是否为'0',为0的话就是新建的项目
            $scope.para = {
                productId : idIndex,
                productName : $scope.newProductName,
                description : $scope.newProductDes,
                personKeyAndRoles: {"TM":tm_map,"DE":de_map}
            };
            var productList = JSON.parse(localStorage.getItem("productList"));
            if (productList === null || productList === undefined){
                productList = [];
            }
            productList.push($scope.para);

            localStorage.setItem("productList",JSON.stringify(productList));
            $scope.confirmModal(true,"产品创建成功!");
            $scope.productId = idIndex;
        };

        //创建流水线的方法
        $scope.createPipeLine = function(){
            if($scope.productId === null || $scope.productId === undefined){
                $scope.confirmModal(false,"请先成功执行项目启动部分的保存动作 !");
                return;
            }
            //将流水线配置保存到后台
            $scope.vm.isUpdate = true;
            $scope.para.pipeLine =$scope.vm;

            var productList = JSON.parse(localStorage.getItem("productList"));
            if (productList !== undefined || productList !== null || productList.length !==0) {
                angular.forEach(productList,function (item) {
                   if (item.productId === idIndex){
                       item.pipeLine = $scope.vm;
                   }
                });
                localStorage.setItem("productList",JSON.stringify(productList));
            }
            //创建成功的提升对话框
            $scope.confirmModal(true,"流水线创建成功!");
        };

        //修改流水线的方法(同时保存项目启动部分的修改内容)
        $scope.updatePipeLine = function(){
            //将修改后的流水线配置保存到后台
            $scope.para.pipeLine =$scope.vm;

            var productList = JSON.parse(localStorage.getItem("productList"));
            if (productList !== undefined || productList !== null || productList.length !==0) {
                angular.forEach(productList,function (item) {
                    if (item.productId === idIndex){
                        item.pipeLine = $scope.vm;
                    }
                });
                localStorage.setItem("productList",JSON.stringify(productList));
            }
            $scope.confirmModal(true,"流水线更新成功!");
        };

        //确认对话框定义
        $scope.confirmModal = function(result,confirmInfo){
            var para = {
                result : result,
                info : confirmInfo
            };
            var modalInstance = $modal.open({
                templateUrl : 'confirm.html',
                controller : confirmCtrl,
                windowClass: "confirmModal",
                keyboard : true,
                backdrop : true,
                resolve : {
                    para : function () {
                        return angular.copy(para);
                    }
                }
            });
            modalInstance.result.then(function() {
                //点击确认按钮之后的进行的操作

            });
        };
        var jiras = JSON.parse(localStorage.getItem("jira"));
        if (jiras === null || jiras === undefined || jiras.length === 0 ){
            $scope.allJira = [
                {code:"CrossData",name:"CrossData"},
                {code:"BDOC",name:"BDOC"},
                {code:"MT",name:"MT"}
            ];
        } else {
            $scope.allJira = angular.copy(jiras);
        }

        $scope.saveProductJiraUrl = function () {
            var productList = JSON.parse(localStorage.getItem("productList"));
            if (productList === null || productList === undefined || productList.length ===0){
                $scope.confirmModal(true,"请先创建产品!");
                return;
            }
            angular.forEach(productList,function (item) {
               if (item.productId === idIndex){
                   item.jira = {
                       url:$scope.selectedJira.jiraUrl,
                       code : $scope.selectedJira.code,
                       name:$scope.selectedJira.name
                   }
               }
            });
            $scope.product.jiraUrl = $scope.selectedJira.jiraUrl;
            $scope.product.jiraCode = $scope.selectedJira.code;
            $scope.product.jiraName = $scope.selectedJira.name;
            localStorage.setItem("productList",JSON.stringify(productList));
            $scope.jiraShowType= 'detail';
        };

        $scope.jiraTasks =
            {
                tasks:
                    {
                        open:
                            [
                                {
                                    type:"bug",number:"CD-1062",level:"major",summary:"互联网环境，抽取MySQL、Oracle报错：Can not create a Path from a null string",userName:"1"
                                },
                                {
                                    type:"bug",number:"CD-428",level:"major",summary:"内蒙古项目环境中，CD报Connection reset错误",userName:"3"
                                },
                                {
                                    type:"improve",number:"CD-234",level:"major",summary:"Teradata抽取装载需要使用Load方式",userName:"9"
                                }
                            ],
                        doing:
                            [
                                {
                                    type:"improve",number:"CD-248",level:"minor",summary:"请进一步提升Oracle抽取装载性能",userName:"12"
                                },
                                {
                                    type:"task",number:"CD-1014",level:"blocker",summary:"广域网性能测试中，需要对比多线程的UDT、TCP以及FTP传输速度",userName:"1"
                                },
                                {
                                    type:"task",number:"CD-1087",level:"major",summary:"当抽取装载含主键的hugetable表时，作业失败",userName:"1"
                                },
                                {
                                    type:"improve",number:"CD-970",level:"minor",summary:"CD1.4.4，ORACLE<->HIVE，抽取装载一级分区HIVE表失败",userName:"9"
                                },
                                {
                                    type:"improve",number:"CD-642",level:"major",summary:"需在cd日志里打印出具体的错误信息，而不仅仅是显示yarn作业运行失败的结果",userName:"12"
                                }
                            ],
                        close:
                            [
                                {
                                    type:"task",number:"CD-1039",level:"minor",summary:"更新crossdata产品手册",userName:"3"
                                },
                                {
                                    type:"new",number:"CD-1029",level:"major",summary:"数据库抽取组件，需要支持单节点连接场景",userName:"1"
                                }
                            ],
                    },
                other:
                    {
                        open:
                            [
                                {
                                    type:"improve",number:"CD-982",level:"major",summary:"同一台机器上进行文件合并，需要专项优化",userName:"1"
                                }
                            ],
                        doing:
                            [
                                {
                                    type:"improve",number:"CD-867",level:"major",summary:"MySQL Writer中，需要优化错误数据判断方法",userName:"3"
                                },
                                {
                                    type:"new",number:"CD-734",level:"major",summary:"高速数据传输工具基本传输功能开发",userName:"3"
                                },
                                {
                                    type:"new",number:"CD-545",level:"major",summary:"支持HVIE2HIVE功能",userName:"12"
                                }
                            ],
                        close:
                            [
                                {
                                    type:"new",number:"CD-1087",level:"major",summary:"支撑IT支撑部性能管理系统生产环境异常",userName:"9"
                                },
                                {
                                    type:"new",number:"CD-1092",level:"major",summary:"RDBEngine支持通用JDBC传输",userName:"3"
                                },
                                {
                                    type:"task",number:"CD-1089",level:"major",summary:"申请开通虚拟机访问物理机权限",userName:"12"
                                },
                                {
                                    type:"improve",number:"CD-1083",level:"major",summary:"类型校验支持datetime和time",userName:"9"
                                },
                                {
                                    type:"improve",number:"CD-1081",level:"major",summary:"timestamp类型校验不起作用",userName:"3"
                                }
                            ],

                    }
            };

        $scope.changeJiraType = function (type) {
            $scope.jiraShowType = type;
        };

        //日期控件
        $scope.openBeginDate = function($event, i) {
            $event.preventDefault();
            $event.stopPropagation();
            if(i==1){
                $scope.beginDate = true;
            }
        };

        $scope.openEndDate = function($event, i) {
            $event.preventDefault();
            $event.stopPropagation();
            if(i==1){
                $scope.endDate = true;
            }
        };

        //画柱形图表
        $scope.chart2 = new h5Charts.SerialChart();
        $scope.chart21 = new h5Charts.SerialChart();
        $scope.chart22 = new h5Charts.SerialChart();
        $scope.initTable2 = function(){

            var dataProvider = [];
            var dataProvider2 = [];
            var colorList = [];

            var codeInfoList =
                [
                    {coderName:"廖光贤",requirementsNum:"10"},
                    {coderName:"王玉雷",requirementsNum:"2"},
                    {coderName:"李宏源",requirementsNum:"3"},
                    {coderName:"张巧龙",requirementsNum:"5"},
                ]
            var costTimeList =
                [
                    {coderName:"廖光贤",costTime:"0.3"},
                    {coderName:"王玉雷",costTime:"0.2"},
                    {coderName:"李宏源",costTime:"0.3"},
                    {coderName:"张巧龙",costTime:"0.5"},
                ]
            if($scope.jiraBeginDate !== null && $scope.jiraBeginDate !== undefined){

            }
            if($scope.jiraEndDate !== null && $scope.jiraEndDate !== undefined){

            }
            angular.forEach(codeInfoList,function (item) {
                var obj = {};
                obj.name = item.coderName ;
                obj.num = item.requirementsNum ;
                dataProvider.push(obj);
                colorList.push("#00B47A");
            });

            angular.forEach(costTimeList,function (item) {
                var obj2 = {};
                obj2.name = item.coderName ;
                obj2.num = item.costTime ;
                dataProvider2.push(obj2);
            });

            if (dataProvider != null && dataProvider.length > 0){
                $scope.chart2.dataProvider = dataProvider;
                $scope.chart2.categoryField = "name";
                $scope.chart2.valueField = "num";
                $scope.chart2.type = "column";
                $scope.chart2.columnWidth = 10;
                $scope.chart2.colors = colorList;
                $scope.chart2.addTo("requirementdone");
            }
            if (dataProvider2 != null && dataProvider2.length > 0){

                $scope.chart22.dataProvider = dataProvider2;
                $scope.chart22.categoryField = "name";
                $scope.chart22.valueField = "num";
                $scope.chart22.type = "column";
                $scope.chart22.columnWidth = 10;
                $scope.chart22.colors = colorList;
                $scope.chart22.addTo("costtime");
            }
        };

        $scope.initTable2();

        $scope.findJiraInfo = function () {
            //清空画布内容
            var canvas1=document.getElementById("requirementdone");
            var cxt1=canvas1.getContext("2d");
            cxt1.clearRect(0,0,canvas1.width,canvas1.height);

            var canvas3=document.getElementById("costtime");
            var cxt3=canvas3.getContext("2d");
            cxt3.clearRect(0,0,canvas3.width,canvas3.height);

            $scope.initTable2();
        }

        $scope.allScmType =
            [
                {key:"gerrit",value:"GERRIT"},
                {key:"svn",value:"SVN"},
                {key:"gitlab",value:"GITLAB"}
            ];
        $scope.changeScm = function () {
            $scope.allScmRepo = [];
            var scmRepos = JSON.parse(localStorage.getItem("scmRepos"));
/*            if (scmRepos === null || scmRepos === undefined || scmRepos.length === 0){
                $scope.confirmModal(true,"请检查资源管理中的scm数据!");
                return;
            }
            angular.forEach(scmRepos,function (item) {
                if (item.type === $scope.scmType.key){
                    $scope.allScmRepo.push(item);
                }
            });*/
            if ("gerrit" === $scope.scmType.key){
                $scope.allScmRepo =    [
                        {scmUrl:"111111",type:"gerrit",name:""},
                        {scmUrl:"222222",type:"gerrit",name:""},
                        {scmUrl:"333333",type:"gerrit",name:""}
                    ];
            } else if("svn" === $scope.scmType.key){
                $scope.allScmRepo =
                    [
                        {scmUrl:"444444",type:"svn",name:"YQ"},
                        {scmUrl:"555555",type:"svn",name:"BC-Stream"},
                        {scmUrl:"666666",type:"svn",name:"BC-SE"}
                    ];
            } else {
                $scope.allScmRepo =
                    [
                        {scmUrl:"444444",type:"gitlab",name:"CrossData"},
                        {scmUrl:"555555",type:"gitlab",name:"PDM"},
                        {scmUrl:"666666",type:"gitlab",name:"ETL"}
                    ];
            }
        };

        $scope.saveProductScmUrl = function () {
            var productList = JSON.parse(localStorage.getItem("productList"));
            if (productList !== undefined || productList !== null || productList.length !==0) {
                angular.forEach(productList,function (item) {
                    if (item.productId === idIndex){
                        item.scm = {
                            url:$scope.selectedScm.scmUrl,
                            type:$scope.selectedScm.type,
                            name:$scope.selectedScm.name,
                        }
                    }
                });
                localStorage.setItem("productList",JSON.stringify(productList));
                $scope.confirmModal(true,"研发过程-SCM配置成功!");
            }
            $scope.scmShowType= 'detail';
        };

        $scope.changeScmType = function (type) {
            $scope.scmShowType = type;
        };

        //画柱形图表
        $scope.codeInfoChar = new h5Charts.SerialChart();
        $scope.initCodeInfo = function(){

            var dataProvider1 = [];
            var colorList = [];
            var commitInfoList =
                [
                    {name:"廖光贤",num:"1230"},
                    {name:"王玉雷",num:"280"},
                    {name:"李宏源",num:"690"},
                    {name:"张巧龙",num:"300"},
                ];
            if ($scope.scmBeginDate !== null && $scope.scmBeginDate !== undefined){


            }
            if ($scope.scmEndDate !== null && $scope.scmEndDate !== undefined){


            }
            if (commitInfoList != null && commitInfoList.length > 0){
                angular.forEach(commitInfoList,function (item) {
                    colorList.push("#00B47A");
                    var obj = {
                        name:item.name,
                        num:item.num
                    };
                    dataProvider1.push(obj);
                });
            }
            if (dataProvider1 != null && dataProvider1.length > 0){
                $scope.codeInfoChar.dataProvider = dataProvider1;
                $scope.codeInfoChar.categoryField = "name";
                $scope.codeInfoChar.valueField = "num";
                $scope.codeInfoChar.type = "column";
                $scope.codeInfoChar.columnWidth = 10;
                $scope.codeInfoChar.colors = colorList;
                $scope.codeInfoChar.addTo("codenumsubmit");
            }
        };

        $scope.initCodeInfo();

        //清空画布内容
        $scope.findCodeInfo = function (){
            var canvas=document.getElementById("codenumsubmit");
            var cxt=canvas.getContext("2d");
            cxt.clearRect(0,0,canvas.width,canvas.height);

            $scope.initCodeInfo();
        };

        var containers = localStorage.getItem("containers");
        if (containers === null || containers === undefined || containers.length === 0){
            /*$scope.confirmModal(true,"请检查资源管理中的容器数据!");
            return;*/
            $scope.allDailyJenkinsType =
                [
                    {key:"jinkins1",value:"dev_jenkins_crossdata"},
                    {key:"jinkins2",value:"容器2"},
                    {key:"jinkins3",value:"容器3"}
                ];
        } else {
            $scope.allDailyJenkinsType = angular.copy(containers);
            $scope.allDailyJenkinsType =
                [
                    {key:"jinkins1",value:"dev_jenkins_crossdata"},
                    {key:"jinkins2",value:"容器2"},
                    {key:"jinkins3",value:"容器3"}
                ];
        }


        $scope.changeDailyJenkins = function () {
            if ("jinkins1" === $scope.dailyJenkinsType.key){
                $scope.allJenkinsRepo =
                    [
                        {taskId:"1",taskName:"crossdata_java"}]
            } else if("jinkins2" === $scope.dailyJenkinsType.key){
                $scope.allJenkinsRepo =
                    [
                        {taskId:"2",taskName:"php_covrage"},
                        {taskId:"3",taskName:"find_bugs"},
                        {taskId:"4",taskName:"builds"}
                    ];
            } else {
                $scope.allJenkinsRepo =
                    [
                        {taskId:"1",taskName:"py_covrage"},
                        {taskId:"3",taskName:"find_bugs"},
                        {taskId:"4",taskName:"builds"}
                    ];
            }
        };

        $scope.saveProductDailyJenkinsUrl = function () {
            var productList = JSON.parse(localStorage.getItem("productList"));
            if (productList !== undefined || productList !== null || productList.length !==0) {
                angular.forEach(productList,function (item) {
                    if (item.productId === idIndex){
                        item.jenkins = {
                            taskId:$scope.selectedJenkins.taskId,
                            taskName:$scope.selectedJenkins.taskName,
                        }
                    }
                });
                localStorage.setItem("productList",JSON.stringify(productList));
                $scope.confirmModal(true,"研发过程-JENKINS配置成功!");
            }
            $scope.dailyJenkinsShowType= 'detail';
        };

        $scope.changeDailyJenkinsType = function (type) {
            $scope.dailyJenkinsShowType = type;
        };

        $scope.files =
            [
                {name:"conf",type:"folder",lastComment:"init project",lastUpdate:""},
                {name:"src",type:"folder",lastComment:"bug fixed",lastUpdate:""},
                {name:".gitignore",type:"file",lastComment:"init project",lastUpdate:""},
                {name:"pom.xml",type:"file",lastComment:"init project",lastUpdate:""}
            ];

        $scope.allScmBranch =
            [
                {name:"dev",id:2},
                {name:"1.0.0-relase",id:3}
            ];

        $scope.allCommints =
            [
                {
                    time : "2017-05-03",
                    commits : [
                        {comment:"修正Jira问题",userName:"吴鹏展",commitId:"68b2159b"},
                        {comment:"修正页面显示问题",userName:"汪诚益",commitId:"6ae4cbca"}
                    ]
                },
                {
                    time : "2017-05-02",
                    commits : [
                        {comment:"后台问题处理",userName:"邵琦",commitId:"88d40bb2"},
                        {comment:"修正登陆错误提示",userName:"汪诚益",commitId:"fd1b5830"},
                        {comment:"修正登陆错误提示",userName:"汪诚益",commitId:"874590ef"}
                    ]
                }
            ];

        $scope.allTags =
            [
                {
                    name:"JX_CrossData_1.4.5_20161221",
                    comment:"Merge branch 'cherry-pick-cf89d344' into 'release-bc-crossdata-1.4.5'",
                    date:"",
                    id:"4b846780"
                }
            ];

        var manageData = [
            {
                "name": "需求文档",
                "vesion": "V1.0.0",
                "status": "TRUE",
                "updateTime": "2017-05-11"
            },{
                "name": "用户使用手册",
                "vesion": "V2.0.0",
                "status": "TRUE",
                "updateTime": "2017-05-09"
            },{
                "name": "框架文档",
                "vesion": "",
                "status": "FALSE",
                "updateTime": ""
            },{
                "name": "安装部署手册",
                "vesion": "",
                "status": "FALSE",
                "updateTime": ""
            },{
                "name": "管理员使用手册",
                "vesion": "V1.0.0",
                "status": "TRUE",
                "updateTime": "2017-05-11"
            },{
                "name": "发布说明",
                "vesion": "",
                "status": "",
                "updateTime": ""
            }
        ];
        var researchData = [
            {
                "status": "Success",
                "name": "crossdata_java",
                "LastSuccess": "3 hr ago",
                "LastFailure": "7 days ago",
                "LastDuration": "8 min 0 sec"
            }, {
                "status": "Failure",
                "name": "crossdata_findbugs",
                "LastSuccess": "11 hr ago",
                "LastFailure": "8 min ago",
                "LastDuration": "3 min 25 sec"
            }, {
                "status": "Success",
                "name": "crossdata_builds",
                "LastSuccess": "10 hr ago",
                "LastFailure": "2 days ago",
                "LastDuration": "5 min 12 sec"
            }, {
                "status": "Success",
                "name": "crossdata_clover",
                "LastSuccess": "13 hr ago",
                "LastFailure": "5 days ago",
                "LastDuration": "1 min 10 sec"
            }
        ];
        function operateFormatter() {
            return [
                '<a class="upload " href="javascript:void(0)" title="Upload">',
                '上传',
                '</a>',
                '<a class="download" style="margin-left: 16px;" href="javascript:void(0)" title="Download">',
                '下载',
                '</a>'
            ].join('');
        }

        window.operateEvents = {
            'click .upload': function (e, value, row, index) {
                $scope.upload(row);
            },
            'click .download': function (e, value, row, index) {
                $scope.download(row);
            }
        };
        function initTable() {
            //初始化manage table
            $('#manageInfo').bootstrapTable({
                data: manageData,
                striped: true,
                cache: false,
                pagination: false,
                sidePagination: 'client',
                pageNumber: 1,
                pageSize: 10,
                uniqueId: true,
                cardView: false,
                columns: [
                    {
                        field: 'name',
                        title: '文档名称'
                    }, {
                        field: 'vesion',
                        title: '版本号'
                    }, {
                        field: 'status',
                        title: '状态'
                    }, {
                        field: 'updateTime',
                        title: '更新日期'
                    }, {
                        field: 'operation',
                        title: '操作',
                        events: operateEvents,
                        formatter: operateFormatter
                    }]
            });
            //初始化research table
            $('#researchInfo').bootstrapTable({
                data: researchData,
                striped: true,
                cache: false,
                pagination: false,
                sidePagination: 'client',
                pageNumber: 1,
                pageSize: 10,
                uniqueId: true,
                cardView: false,
                columns: [
                    {
                        field: 'status',
                        title: '状态'
                    }, {
                        field: 'name',
                        title: '名称'
                    }, {
                        field: 'LastSuccess',
                        title: 'LastSuccess'
                    }, {
                        field: 'LastFailure',
                        title: 'LastFailure'
                    }, {
                        field: 'LastDuration',
                        title: 'LastDuration'
                    }]
            });
        }
        window.onload = function () {
            initTable();
            initTestTable();
        };

        $scope.getProductTestRecord = function () {
            var productList = JSON.parse(localStorage.getItem("productList"));
            if (productList !== null || productList !== undefined || productList.length !== 0) {
                angular.forEach(productList,function (item) {
                   if (item.productId === idIndex){
                       $scope.tableData = item.testRecords;
                   }
                });
            } else {
                $scope.tableData = [];
            }
            initTestTable();
        };

        var $table = $('#testInfo'),
            $remove = $('#remove'),
            $add = $('#add'),
            $save = $('#save'),
            $refresh = $('#refresh'),
            selections = [];
        function initTestTable() {
                $table.bootstrapTable({
                    data:$scope.tableData,
                    toolbar: '#toolbar',
                    striped: true,
                    cache: false,
                    showRefresh :false,
                    pagination: true,
                    sortable: true,
                    sortOrder: 'asc',
                    search:false,
                    searchAlign:'left',
                    sidePagination: "client",
                    pageNumber: 1,
                    pageSize: 10,
                    pageList: [10, 25, 50, 100],
                    clickToSelect: false,
                    uniqueId: true,
                    cardView: false,
                    detailView: false,
                    responseHandler : responseHandler,
                    columns:[
                        [  {
                            field: 'state',
                            checkbox: true,
                            rowspan: 2,
                            align: 'center',
                            valign: 'middle'
                        },{
                            field: 'test_product_name',
                            title: '产品名称',
                            editable: true,
                            align: 'center',
                            valign: 'middle',
                            rowspan: 2
                        }, {
                            field: 'test_product_version',
                            title: '提测版本',
                            align: 'center',
                            valign: 'middle',
                            editable: true,
                            rowspan: 2
                        }, {
                            field: 'test_dev_caller',
                            title: '提测人',
                            editable: true,
                            align: 'center',
                            valign: 'middle',
                            rowspan: 2
                        }, {
                            field: 'test_call_time',
                            title: '提测时间',
                            /*editable: {
                                type: 'date'
                            },*/
                            editable: true,
                            align: 'center',
                            valign: 'middle',
                            rowspan: 2
                        }, {
                            field: 'test_branch',
                            title: '提测分支',
                            editable: true,
                            align: 'center',
                            valign: 'middle',
                            rowspan: 2
                        } , {
                            field: 'test_executor_name',
                            title: '测试人员',
                            editable: true,
                            align: 'center',
                            valign: 'middle',
                            rowspan: 2
                        } , {
                            field: 'test_report_publish_time',
                            title: '报告时间',
                            /*editable: {
                                type: 'date'
                            },*/
                            editable: true,
                            align: 'center',
                            valign: 'middle',
                            rowspan: 2
                        } , {
                            field: 'smoke_pass_rate',
                            title: '冒烟测试通过率',
                            editable: true,
                            align: 'center',
                            valign: 'middle',
                            rowspan: 2
                        } , {
                            field: 'return_times',
                            title: '退回次数',
                            editable: true,
                            align: 'center',
                            valign: 'middle',
                            rowspan: 2
                        } , {
                            field: 'test_product_config_info',
                            title: '配置信息',
                            editable: true,
                            align: 'center',
                            valign: 'middle',
                            rowspan: 2
                        }, {
                            title: 'Test',
                            align: 'center',
                            valign: 'middle',
                            colspan: 2
                        },  {
                            title: 'Stable',
                            align: 'center',
                            valign: 'middle',
                            colspan: 3
                        }],
                        [{
                            field: 'test_product_test_dir_packages',
                            align: 'center',
                            editable: {
                                type: 'select',
                                title: '部署包',
                                source:[{value:"1",text:"是"},{value:"0",text:"否"}]
                            },
                            valign: 'middle',
                            title: '部署包'
                        },{
                            field: 'test_product_test_dir_license',
                            align: 'center',
                            editable: {
                                type: 'select',
                                title: 'license',
                                source:[{value:"1",text:"是"},{value:"0",text:"否"}]
                            },
                            valign: 'middle',
                            title: 'license'
                        },{
                            field: 'test_product_stable_dir_packages',
                            align: 'center',
                            editable: {
                                type: 'select',
                                title: '部署包',
                                source:[{value:"1",text:"是"},{value:"0",text:"否"}]
                            },
                            valign: 'middle',
                            title: '部署包'
                        },{
                            field: 'test_product_stable_dir_license',
                            align: 'center',
                            editable: {
                                type: 'select',
                                title: 'license',
                                source:[{value:"1",text:"是"},{value:"0",text:"否"}]
                            },
                            valign: 'middle',
                            title: 'license'
                        },{
                            field: 'test_product_docs',
                            align: 'center',
                            editable: {
                                type: 'select',
                                title: '安装部署手册',
                                source:[{value:"1",text:"是"},{value:"0",text:"否"}]
                            },
                            valign: 'middle',
                            title: '安装部署手册'
                        }]
                    ]
                });
            };
        function getIdSelections() {
            return $.map($table.bootstrapTable('getSelections'), function (row) {
                return row
            });
        }
        function cellStyle(value, row, index, field) {
            return {
                classes: 'text-nowrap another-class',
                css: {"color": "blue", "font-size": "50px"}
            };
        }
        function responseHandler(res) {
            $.each(res.data, function (i, row) {
                row.state = $.inArray(row.id, selections) !== -1;
            });
            return res;
        }

        $table.on('check.bs.table uncheck.bs.table ' +
            'check-all.bs.table uncheck-all.bs.table', function () {
            $remove.prop('disabled', !$table.bootstrapTable('getSelections').length);
            // save your data, here just save the current page
            selections = getIdSelections();
            // push or splice the selections if you want to save all data selections
        });
        $remove.click(function () {
            var rows = getIdSelections();
            var list = [];
            var deleteList = [];
            angular.forEach(rows,function (row) {
                if(row.id == null){
                    list.push(true);
                } else {
                    var item = {id:row.id};
                    deleteList.push(item);
                }
            });
            if(list.length > 0){
                $table.bootstrapTable('remove', {field: 'state', values: list});
                $scope.confirmModal(true,"删除成功");
            }
            if(deleteList.length > 0){
                var productList = JSON.parse(localStorage.getItem("productList"));
                if (productList !== null || productList !== undefined || productList.length > 0){
                    angular.forEach(productList,function (item) {
                        if (item.productId === idIndex){
                            var records = angular.copy(item.testRecords);
                            var index = 0;
                            angular.forEach(records,function (record) {
                                angular.forEach(deleteList,function (row) {
                                    if (record.id === row.id){
                                        records.splice(index,1);
                                        index -- ;
                                    }
                                    index++;
                                });
                            });
                            item.testRecords = records;
                            localStorage.setItem("productList",JSON.stringify(productList));
                        }
                    });
                }
                $scope.confirmModal(true,"删除成功");
                $table.bootstrapTable('destroy');
                $scope.getProductTestRecord();
            }
        });
        $refresh.click(function () {
            $table.bootstrapTable('destroy');
            $scope.getProductTestRecord();
        });
        // yyyy-mm-dd hh:mm:ss格式的正则表达式
        // var timePatten = /^((((1[6-9]|[2-9]\d)\d{2})-(0?[13578]|1[02])-(0?[1-9]|[12]\d|3[01]))|(((1[6-9]|[2-9]\d)\d{2})-(0?[13456789]|1[012])-(0?[1-9]|[12]\d|30))|(((1[6-9]|[2-9]\d)\d{2})-0?2-(0?[1-9]|1\d|2[0-8]))|(((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))-0?2-29-)) (20|21|22|23|[0-1]?\d):[0-5]?\d:[0-5]?\d$/;

        $save.click(function () {
            $scope.hasError = false;
            $scope.errorMsgs = [];
            var tableData  = $table.bootstrapTable('getData');
            if (tableData === null || tableData === undefined || tableData.length === 0 ){
                $scope.confirmModal(true,"请填写数据");
                return;
            }
            for(var i=0;i<tableData.length;i++){
                var j = i+1;
                var row = tableData[i];
                row.product = {};
                if(row.smokePassRate != null && row.smokePassRate != undefined && $.trim(row.smokePassRate) != ""){
                    var spr = Number(row.smokePassRate);
                    if(isNaN(spr) || !angular.isNumber(spr)){
                        $scope.errorMsgs.push("第"+j+"条数据，冒烟测试通过率必须为数字");
                        $scope.hasError = true;
                    } else {
                        if(spr > 100 || spr < 0){
                            $scope.errorMsgs.push("第"+j+"条数据，冒烟测试通过率必须为在0~100之间");
                            $scope.hasError = true;
                        }
                    }
                }

                if(row.returnTimes != null && row.returnTimes != undefined && $.trim(row.returnTimes) != ""){
                    var rt = Number(row.returnTimes);
                    if(isNaN(rt) || !angular.isNumber(rt)){
                        $scope.errorMsgs.push("第"+j+"条数据，退回次数必须为数字");
                        $scope.hasError = true;
                    } else {
                        if(rt < 0){
                            $scope.errorMsgs.push("第"+j+"条数据，退回次数必须大于0");
                            $scope.hasError = true;
                        }
                    }
                }
            }
            if($scope.hasError){
                if ($scope.errorMsgs.length > 5){
                    $scope.errorMsgs = $scope.errorMsgs.splice(0,5);
                }
                $scope.$apply();
            }
            if(!$scope.hasError){
                var productList = JSON.parse(localStorage.getItem("productList"));
                if (productList !== null || productList !== undefined || productList.length > 0){
                    angular.forEach(productList,function (item) {
                        if (item.productId === idIndex){
                            var index = tableData[tableData.length - 1].id;
                            if (index === null || index === undefined){
                                index = 0;
                            }
                            angular.forEach(tableData,function (row) {
                                if (row.id === null || row.id === undefined){
                                    index++;
                                    row.id = index;
                                }
                            });
                            item.testRecords = tableData;
                        }
                    });
                    localStorage.setItem("productList",JSON.stringify(productList));
                }
                $scope.confirmModal(true,"保存成功");
                $table.bootstrapTable('destroy');
                $scope.getProductTestRecord();
            }
        });
        $add.click(function () {
            var data = initNewRow();
            $table.bootstrapTable('insertRow', {index: 0, row: data});
        });
        function initNewRow() {
            var pn = "";
            if($scope.newProductName != null){
                pn = $scope.newProductName;
            }
            return {
                state:false,
                test_product_name:pn,
                test_product_version:"",
                test_dev_caller:"",
                test_call_time:null,
                test_branch:"",
                test_executor_name:"",
                test_report_publish_time:null,
                smoke_pass_rate:"",
                return_times:"",
                test_product_config_info:"",
                test_product_test_dir_packages:"0",
                test_product_test_dir_license:"0",
                test_product_stable_dir_packages:"0",
                test_product_stable_dir_license:"0",
                test_product_docs:"0"
            };
        }
        $scope.changeTestType = function (type) {
            $scope.testShowType = type;
        };
    };

    var confirmCtrl = ["$scope","$modal", "$modalInstance","para",function($scope,
        $modal, $modalInstance, para) {
        $scope.result = para.result;
        $scope.info = para.info;

        $scope.ok = function() {
            $modalInstance.close();
        };
        $scope.cancel = function() {
            $modalInstance.dismiss('cancel');
        };
    }];

    var modalInstanceCtrl = ["$scope","$modal", "$modalInstance", "paras",function($scope,
        $modal, $modalInstance, paras) {

        //日期控件
        $scope.dateOptions = {
             startingDay: 1,
             class: 'datepicker'
        };
        //日期控件
        $scope.format = "yyyy-MM-dd";
        $scope.openDatepicker = function($event, i) {
            $event.preventDefault();
            $event.stopPropagation();
            if(i==1){
                $scope.loanDate = true;
            }
        };

        $scope.openDatepicker1 = function($event, i) {
            $event.preventDefault();
            $event.stopPropagation();
            if(i==1){
                $scope.loanDate1 = true;
            }
        };

        $scope.pros = paras.pros;
        $scope.opers = paras.teststarters;
        $scope.operators = paras.testers;

        //入参的产品，提测人，测试负责人改成对象
        $scope.newTestStartRecord = {
            production :  $scope.selectedProduct,
            versionNum :  "",
            testStarter : $scope.selectedTestStarter,
            loanDate : "",
            branchName : "",
            tester : $scope.selectedTester,
            loanDate1 :  "",
            smokeTestPassRate : "",
            returnNum :  "",
            configInfo :  ""
        };

        $scope.ok = function() {
            $modalInstance.close($scope.newTestStartRecord);
        };
        $scope.cancel = function() {
            $modalInstance.dismiss('cancel');
        };
    }];

    var uploadController=["$scope","$modal", "$modalInstance","items","AcceptanceService",
        function ($scope, $modal,$modalInstance,items,acceptanceService) {
            $scope.item = items.item;
            $scope.cancel = function () {
                $modalInstance.dismiss('cancel');
            };
            $scope.upload = function () {
                var fd = new FormData();
                var files = document.querySelector('input[type=file]').files;
                if(files.length == 0){
                    $scope.loading = false;
                    $.Huimodalalert("请选择要上传的文件",1000);
                    return;
                }
                angular.forEach(files,function (file) {
                    fd.append('file[]', file);
                });
                fd.append('id',$scope.item.id);
                acceptanceService.upload(fd).success(function (data) {
                    if(data.errorMsg != null){
                        alert(data.errorMsg);
                    } else {
                        alert("上传成功！");
                        //关闭
                        $modalInstance.close($scope.item);
                    }
                });
            };
        }
    ];

    angular.module("cicd.config.manage",[])
        .controller("ConfigManageController",["$scope","$http","$modal","$location","projectstart_Service","online_testService",
            "develop_processService","online_deliveryService","AcceptanceService","toolsService",configManageController])
})();